import { dayjs } from 'element-plus'
import { merge } from 'lodash-es'

interface HookOptions {
  unix?: boolean
  range?: boolean
}

type DateValue =
  | string
  | number
  | [string | number | Date, string | number | Date]
  | undefined

const defaultOptions: HookOptions = {
  unix: false,
  range: true
}

export default function useRangeDate(options?: HookOptions) {
  options = merge(defaultOptions, options)

  const value = ref<number | undefined>(0)

  const unit = ref<dayjs.ManipulateType>('day')

  const date = ref<DateValue>()

  const data = computed(() => {})

  function calcDate() {
    if (typeof value.value === 'undefined') {
      return
    }
    const formatTemplate = 'YYYY-MM-DD HH:mm:ss'
    if (options?.range) {
      let d1 = dayjs()
      let d2 = dayjs()
      if (value.value >= 0) {
        d2 = d2.add(value.value, unit.value)
      } else {
        d1 = d1.subtract(value.value, unit.value)
      }
      date.value = [d1.format(formatTemplate), d2.format(formatTemplate)]
      return
    }
    date.value = dayjs().add(value.value, unit.value).format(formatTemplate)
  }

  watchEffect(() => {
    calcDate()
    // console.log(date.value)
  })

  return { value, unit, date, data }
}
